from django.shortcuts import render
from django.views import View
from django.conf import settings
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
import json
from django.core import serializers
# from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

from .models import CourseOrg, City
from .forms import AddAskForm
from apps.operation.models import UserFavorite

# 课程描述
class OrgDescView(View):
    def get(self, request, org_id=1, *args, **kwargs):
        current_page = 'desc'
        course_org = CourseOrg.objects.get(id=org_id)  # 因为传过来的 org_id 肯定存在，所以用 get 方式
        course_org.click_nums += 1  # 点击数增加
        course_org.save()

        has_fav = False  # 用以判断用户是否收藏
        if request.user.is_authenticated:
            # 如果用户已收藏
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        return render(request, 'org-detail-desc.html', {
            "current_page": current_page,
            "course_org": course_org,
            "has_fav": has_fav
        })

# 机构课程
class OrgCourseView(View):
    def get(self, request, org_id=1, *args, **kwargs):
        current_page = 'course'
        course_org = CourseOrg.objects.get(id=org_id)  # 因为传过来的 org_id 肯定存在，所以用 get 方式
        course_org.click_nums += 1  # 点击数增加
        course_org.save()

        has_fav = False  # 用以判断用户是否收藏
        if request.user.is_authenticated:
            # 如果用户已收藏
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        all_courses = course_org.course_set.all()  # 取得该机构下的 所有课程

        # 处理分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页, 每页显示5条数据
        p = Paginator(all_courses, 1)
        all_courses = p.page(page)

        return render(request, 'org-detail-course.html', {
            "current_page": current_page,
            "course_org": course_org,
            "all_courses": all_courses,
            "has_fav": has_fav
        })


# 机构讲师
class OrgTeacherView(View):
    def get(self, request, org_id=1, *args, **kwargs):
        current_page = 'teacher'
        course_org = CourseOrg.objects.get(id=org_id)  # 因为传过来的 org_id 肯定存在，所以用 get 方式
        course_org.click_nums += 1  # 点击数增加
        course_org.save()

        has_fav = False  # 用以判断用户是否收藏
        if request.user.is_authenticated:
            # 如果用户已收藏
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        all_teacher = course_org.teacher_set.all()  # 取得该机构下的 所有讲师

        return render(request, 'org-detail-teachers.html', {
            "current_page": current_page,
            "course_org": course_org,
            "all_teacher": all_teacher,
            "has_fav": has_fav
        })


# 机构详情页
class OrgHomeView(View):
    def get(self, request, org_id=1, *args, **kwargs):  # 取不到 org_id 就默认取 1
        current_page = 'home'
        course_org = CourseOrg.objects.get(id=org_id)  # 因为传过来的 org_id 肯定存在，所以用 get 方式
        course_org.click_nums += 1  # 点击数增加
        course_org.save()

        has_fav = False  # 用以判断用户是否收藏
        if request.user.is_authenticated:
            # 如果用户已收藏
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        all_courses = course_org.course_set.all()[:3]  # 取得该机构下的 前三个课程
        all_teacher = course_org.teacher_set.all()[:1]  # 取得该机构下的 前一个讲师

        return render(request, 'org-detail-homepage.html', {
            "current_page": current_page,
            "course_org": course_org,
            "all_courses": all_courses,
            "all_teacher": all_teacher,
            "has_fav": has_fav
        })


# 用户咨询
class AddAskView(View):
    def post(self, request, *args, **kwargs):
        '''
        处理用户咨询
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        userask_form = AddAskForm(request.POST)
        if userask_form.is_valid():
            # 表单验证通过立即保持数据
            user_ask = userask_form.save(commit=True)  # commit=True 表示立即执行保存操作
            return JsonResponse({
                'status': 'success'
            })
        else:
            return JsonResponse({
                'status': 'fail',
                # 'msg': '添加出错'
                'msg': userask_form.errors['mobile']
            })


# 授课机构列表页
class OrgView(View):
    # get 请求
    def get(self, request, *args, **kwargs):
        # 从数据库中取得课程机构的数据
        all_orgs = CourseOrg.objects.all()
        all_citys = City.objects.all()

        # 授课机构排名，按点击数进行排名,只截取前三
        hot_orgs = all_orgs.order_by('-click_nums')[:3]

        # 按照机构类别对课程机构进行筛选
        category = request.GET.get('ct', '')  # 如果是按地址筛选时，前端不会传递 ct 参数，所以这里设置默认值为空
        if category:
            all_orgs = all_orgs.filter(category=category)

        # 按照所在城市对课程机构进行筛选
        city_id = request.GET.get('city', '')  # 如果是按地址筛选时，前端不会传递 ct 参数，所以这里设置默认值为空
        if city_id and city_id.isdigit():  # 当 city_id 存在切是数字类型时进一步筛选数据
            all_orgs = all_orgs.filter(city_id=int(city_id))  # 因为前端传递过来的是字符串类型

        # 对课程机构进行排序
        sort = request.GET.get('sort', '')
        if sort == 'students':
            all_orgs = all_orgs.order_by('-students')  # 加 - 表示降序
        if sort == 'courses':
            all_orgs = all_orgs.order_by('-course_nums')

        # 处理分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页, 每页显示5条数据
        p = Paginator(all_orgs, 5)
        all_orgs = p.page(page)

        return render(request, 'org-list.html', {
            'all_orgs': all_orgs,
            'all_citys': all_citys,
            'category': category,
            'city_id': city_id,
            'sort': sort,
            'hot_orgs': hot_orgs
        })

    def post(self, request, *args, **kwargs):
        response = {}
        page = request.POST['page']

        all_orgs = CourseOrg.objects.all()

        paginator = Paginator(all_orgs, 1)

        response['totalCount'] = paginator.count
        # 每页显示条数
        response['numPerPage'] = 1
        # 总共页数
        response['totalPage'] = paginator.num_pages
        # 获取指定页码的数据
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)
        # 当前多少页
        response['pageNum'] = users.number
        response['list'] = json.loads(serializers.serialize("json", users.object_list))

        res = {'status': 1, 'message': '获取成功', 'data': response}
        # 将数据返回到页面
        return JsonResponse(res)

        # return JsonResponse({'ok': 'ok'}, content_type='application/json')
